// ws-client.js

export default class WSClient {
  constructor({ url='', protocols = [], reconnectInterval = 5000, maxRetries = 5, heartBeatInterval = 3000,  heartBeatTimeout = 5000,onMessage=null ,
    // 心跳消息的必填字段
    heartBeatMsg={}
    // userType = null,  fromUid = null,toUid=null, channel = null,userId = null,customerType=''
   }) {
    this.url = url
    this.protocols = protocols
    //重连时间间隔
    this.reconnectInterval = reconnectInterval
    //重连最大次数
    this.maxRetries = maxRetries
    //心跳时间间隔
    this.heartBeatInterval = heartBeatInterval
    //心跳超时重连
    this.heartBeatTimeout = heartBeatTimeout

    this.ws = null
    //重连次数
    this.retryCount = 0
    //心跳计时器
    this.heartBeatTimer = null
    //重连计时器
    this.reconnectTimer = null
    //是否需要触发重连
    this.isManuallyClosed = false
    //等待 pong 的倒计时
    this.heartBeatTimeoutTimer = null
    //待发送消息队列
    this.queue = []
    //接收消息回调
    this.onMessage = onMessage

    // 初始化心跳消息（固定格式）
    this.heartBeatMsg = heartBeatMsg
    // this.heartBeatMsg = {
    //   messageType: 99,     // 固定值99表示心跳
    //   userType,            // 发送方类型（由调用方传入）
    //   fromUid,             // 发送方标识（由调用方传入）
    //   toUid,               //当前选择的接收方标识
    //   channel,             // 消息通道标识（由调用方传入）
    //   userId,              // 客服ID（可选）
    //   customerType,        //客服类型（app端、工单系统必传）
    //   linkFrom:'cs_wo'     // 消息来源（mini/app/cs_wo）
    // }
  }

  connect() {
    if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
      console.warn('[WS] 已有连接正在建立或已建立')
      return
    }

    this.isManuallyClosed = false
    this.ws = new WebSocket(this.url, this.protocols)

    this.ws.onopen = () => {
      console.log('[WS] 连接成功')
      this.retryCount = 0
      this.stopReconnect()
       this.startHeartBeat()  // 启动心跳检测
      this.flushQueue()
    }

    this.ws.onmessage = (event) => {
      console.log('[WS] 通信成功', event)
      this.handleMessage(event.data)
    }

    this.ws.onclose = (e) => {
      console.warn('[WS] 连接关闭', e.code, e.reason)
      this.stopHeartBeat()
      if (!this.isManuallyClosed && !this.reconnectTimer) this.tryReconnect()
      this.ws = null
    }

    this.ws.onerror = (err) => {
      console.error('[WS] 通信发生错误', err)
      this.ws.close() // 触发 onclose
    }
  }

  send(data) {
    const payload = typeof data === 'string' ? data : JSON.stringify(data)
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      console.log('发送的消息',payload)
      this.ws.send(payload)
    } else {
      console.log('[WS] 连接未就绪，消息加入队列')
      this.queue.push(payload)
    }

  }
  flushQueue() {
    while (this.queue.length && this.ws && this.ws.readyState === WebSocket.OPEN) {
      const msg = this.queue.shift()
      console.log('[WS]进入消息队列', msg)
      this.ws.send(msg)
    }
  }

  close() {
    this.isManuallyClosed = true
    this.stopHeartBeat()
    this.queue = []
    if (this.ws) {
      this.ws.close()
    }
    this.stopReconnect()
  }
  startHeartBeat() {
    this.stopHeartBeat() // 避免重复
    this.heartBeatTimer = setInterval(() => {
      this.send(this.heartBeatMsg)   // 发送规范的心跳消息
      console.log('[WS] 发送心跳消息')
      // this.startHeartBeatTimeout()
    }, this.heartBeatInterval)
  }
  /* 停止心跳检测 */
  stopHeartBeat() {
    if (this.heartBeatTimer) {
      clearInterval(this.heartBeatTimer)
      this.heartBeatTimer = null
    }
    // clearTimeout(this.heartBeatTimeoutTimer)
    // this.heartBeatTimeoutTimer = null
  }
  // /*  启动心跳超时检测 */
  // startHeartBeatTimeout() {
  //   clearTimeout(this.heartBeatTimeoutTimer)
  //   this.heartBeatTimeoutTimer = setTimeout(() => {
  //     console.log('[WS] 心跳超时，准备重连')
  //     this.ws && this.ws.close()
  //   }, this.heartBeatTimeout)
  // }
  tryReconnect() {
    if (this.retryCount >= this.maxRetries) {
      console.warn('[WS] 达到最大重连次数，停止尝试')
      this.stopReconnect()
      return
    }
    if ( this.reconnectTimer ) return;
    this.reconnectTimer = setTimeout(() => {
      this.retryCount++
      console.log(`[WS] 尝试重连 (${this.retryCount}/${this.maxRetries})...`)
      this.connect()
    }, this.reconnectInterval)
  }
  stopReconnect() {
    clearTimeout(this.reconnectTimer)
    this.reconnectTimer = null
  }
  /* 处理收到的消息 */
  handleMessage(message) {
    let msg = JSON.parse(JSON.parse(message))
    // 检查是否为心跳响应（messageType === 99）
    console.log('接收消息回应',msg)
    if (msg.messageType == 99) {
      console.log('[WS] 收到心跳回应')
      // clearTimeout(this.heartBeatTimeoutTimer)
      return
    }
    // 在这里处理实际业务消息
    // let msg = JSON.parse(JSON.parse(message))
    console.log('[WS] 收到消息:', msg)
    this.onMessage?.(msg)
  }
}
